package com.teapos.service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import jodd.http.HttpRequest;
import jodd.http.HttpResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.teapos.dao.BuyBackDao;
import com.teapos.dao.CustomerDao;
import com.teapos.dao.OrderDao;
import com.teapos.dao.QRcodeDao;
import com.teapos.enumtype.PayTypeEnum;
import com.teapos.enumtype.TradeTypeEnum;
import com.teapos.util.BusinessTool;
import com.teapos.util.Lists;
import com.teapos.util.Maps;
import com.teapos.util.PropUtil;
import com.teapos.util.Tool;

@SuppressWarnings({"rawtypes", "unchecked"})
@Service
public class BuyBackService {
	
	@Autowired
	private BuyBackDao buyBackDao;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private QRcodeDao qRcodeDao;
	@Autowired
	private CustomerDao customerDao;
	

	public Map findOrderItem(String code) {
		Map map = buyBackDao.findOrderItemByCode(code);
		if(map!=null) {
			//散装：0  整装：1
			int unit = Tool.toInt(map.get("myunit"));
			if(unit==0) map.put("new_price", Tool.toInt(map.get("dpxsj"))/100);
			else if(unit==1) map.put("new_price", Tool.toInt(map.get("zjdlj"))/100);
		}
		return map;
	}
	
	@Transactional(propagation=Propagation.REQUIRED, readOnly=false, rollbackFor=Exception.class)
	public void saveOrder(Map param) {
		
		//order:id, order_no, order_date, order_status(0:未撤销1:已撤销), has_save, user_id, user_name, store_id, store_name, 
		//cash_amount, bank_amount, serial_no, vip_amount, vip_no, wipe_amount, sum_amount, pay_amount, sum_buy, sum_save,
		//customer_id, type(1:散客买茶2:会员买茶3:预收款管理4:货品收购5:pad下单)
		String orderId = BusinessTool.generateId();
		String orderNo = BusinessTool.generateOrderNo();
		Map user = (Map)param.get("user");
		Map customer = (Map)param.get("customer");
		Map order = new Maps().put("id", orderId).put("order_no", orderNo).put("has_save", 0).put("user_id", user.get("id"))
				.put("user_name", user.get("username")).put("store_id", user.get("stid"))
				.put("store_name", user.get("store_name")).put("cash_amount", param.get("cash_amount"))
				.put("bank_amount", param.get("bank_amount")).put("wipe_amount", param.get("wipe_amount"))
				.put("sum_amount", param.get("sum_price")).put("sum_buy", param.get("sum_buy"))
				.put("customer_id", customer.get("id")).put("type", TradeTypeEnum.BUY.getCode())
				.put("pay_amount", param.get("pay_amount")).build();
		
		orderDao.saveOrder(order);
//		int payType = Tool.toInt(param.get("pay_type"));
//		if(payType==1) builder.put("cash_amount", param.get("cash_amount")).put("bank_amount", 0);
//		else if(payType==2) builder.put("bank_amount", param.get("bank_amount")).put("cash_amount", 0);
//		builder.put(, value)
		
		//order_item:id, order_id, order_no, qrcode_id, discount, org_price, is_save, product_name, now_price, product_id,
		//unit, create_time
		List products = (List) param.get("products");
		Iterator iter = products.iterator();
		List productList = Lists.newArrayList();
		while(iter.hasNext()) {
			Map product = (Map)iter.next();
			int unit = product.get("myunit").equals("散装")?0:1;
			String orderItemId = BusinessTool.generateId();
			Map item = new Maps().put("id", orderItemId).put("order_id", orderId)
					.put("order_no", orderNo).put("qrcode_id", product.get("qrcode_id"))
					.put("discount", product.get("discount")).put("org_price", product.get("new_price"))
					.put("is_save", 0).put("product_name", product.get("product_name"))
					.put("now_price", product.get("discount_price")).put("product_id", product.get("product_id"))
					.put("unit", unit).build();
			productList.add(item);
			
			buyBackDao.saveBuyBackHistory(Maps.newHashMap("id", BusinessTool.generateId(), "order_item_id", orderItemId
					,"old_order_no", product.get("old_order_no"), "old_price", product.get("old_price")));
			
			//二维码和客户解绑
			qRcodeDao.bindUserCode(Maps.newHashMap("code", product.get("qrcode_id"), "customer_id", 0, "customer_name", 0));
			
			//增加店面库存
			Map data = Maps.newHashMap(product.get("product_id"), Maps.newHashMap("type", 0
			 , "unit", unit, "customerId", 0, "count", -1));
			//System.err.println(JSON.toJSONString(data));
			
			HttpResponse response = HttpRequest
			        .post(PropUtil.getValueByKey("url.stock"))
			        .form("storeId", user.get("store_id"), "data", JSON.toJSONString(data))
			        .send();
			Map result = JSON.parseObject(response.body());
			String msg = Tool.toString(result.get(product.get("product_id")));
			if("error".equals(msg)) throw new RuntimeException("增加库存失败！！");
		}
		orderDao.saveOrderItems(productList);
		//order_buyback:id, order_id, pay_type, bank_no, account_name, bank_name
		Map buyback = new Maps().put("id", BusinessTool.generateId()).put("order_id", orderId)
				.put("buyback_type", param.get("buybackType"))
				.put("pay_type", param.get("pay_type")).put("bank_no", param.get("bank_no"))
				.put("account_name", param.get("account_name")).put("bank_name", param.get("bank_name")).build();
		buyBackDao.saveBuyBackOrder(buyback);
	}

	public List findOrdersByUser(Map map) {
		String name = Tool.toString(map.get("name"));
		String tel = Tool.toString(map.get("tel"));
		if(StringUtils.isNotBlank(name)) map.put("name", "%"+name+"%");
		if(StringUtils.isNotBlank(tel)) map.put("tel", "%"+tel+"%");
		List list = orderDao.findItemsByUser(map);
		System.err.println(list);
		return list;
	}

	public List findQrcodesByIds(String ids) {
		List list = qRcodeDao.findQrcodesByIds(ids);
		Iterator iter = list.iterator();
		
		while(iter.hasNext()) {
			Map map = (Map)iter.next();
			//散装：0  整装：1
			int unit = Tool.toInt(map.get("myunit"));
			if(unit==0) map.put("new_price", Tool.toInt(map.get("dpxsj"))/100);
			else if(unit==1) map.put("new_price", Tool.toInt(map.get("zjdlj"))/100);
			map.put("discount_price", map.get("new_price"));
		}
		return list;
	}

	public Map getOrderDetail(String orderId, String customerId) {
		List products = buyBackDao.findItemsByOrderId(orderId);
		Map customer = customerDao.findCustomerById(customerId);
		Map order = buyBackDao.findOrderByOrderId(orderId);
		order.put("pay_type_display", PayTypeEnum.getEnumByCode(Tool.toInt(order.get("pay_type"))).getDesc());
		return Maps.newHashMap("products", products, "customer", customer, "order", order);
	}

}
